<template>
    <div>
        <el-card shadow="never" :body-style="{ padding: '20px' }">
            <el-form :model="formData" ref="form" label-width="120px" :inline="false">
                <!-- 基本信息区域 -->
                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="计划编码">
                            <el-input v-model="formData.planCode" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="计划名称">
                            <el-input v-model="formData.planName" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="计划类型">
                            <el-radio-group v-model="formData.planType" disabled>
                                <el-radio value="1">订单计划</el-radio>
                                <el-radio value="2">库存计划</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item v-if="formData.planType == 1" label="订单编号">
                            <el-input v-model="formData.salesOrderId" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-divider content-position="left">产品信息</el-divider>


                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="产品编号">
                            <el-input v-model="products.materialId" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="产品名称">
                            <el-input v-model="products.materialName" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="规格型号">
                            <el-input v-model="products.specifications" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="单位">
                            <el-input v-model="products.unit" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8" :offset="0">
                        <el-form-item label="计划数量">
                            <el-input v-model="products.planQuantity" readonly>
                                <template #default="{ row }">
                                    <el-tag>{{ row.planQuantity }}</el-tag>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" :offset="0">
                        <el-form-item label="已完成数量">
                            <el-input v-model="products.completedQuantity" readonly>
                                <template #default="{ row }">
                                    <el-tag :type="row.completedQuantity >= row.planQuantity ? 'success' : 'warning'">
                                        {{ row.completedQuantity }}
                                    </el-tag>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" :offset="0">
                        <el-form-item label="完成进度">
                            <el-input v-model="products.completionRate" readonly>
                                <template #default="{ row }">
                                    <el-progress :percentage="row.completionRate"
                                        :status="row.completionRate >= 100 ? 'success' : 'warning'">
                                    </el-progress>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-divider v-if="formData.planType == 1" content-position="left">客户信息</el-divider>



                <el-row :gutter="20" v-if="formData.planType == 1">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="客户编号">
                            <el-input v-model="formData.customerId" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="客户名称">
                            <el-input v-model="formData.customerName" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="计划开始日期">
                            <el-date-picker v-model="formData.startDate" type="datetime" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="计划结束日期">
                            <el-date-picker v-model="formData.endDate" type="datetime" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>


            <el-tabs type="border-card" class="detail-tabs" @tab-click="handleTabClick">
                <el-button @click="toInsert" type="primary" :plain="true">+添加</el-button>
                <el-button type="success" :plain="true" :disabled="selectedRows.length !== 1"
                    @click="handleUpdate(selectedRows[0])">修改</el-button>
                <el-button type="danger" :plain="true" :disabled="!selectedRows.length"
                    @click="handleBatchDelete">删除</el-button>


                <el-tab-pane v-for="item in proecss" :key="item.processId" :label="item.psName"
                    :value="item.processId" :name="item.processId">
                    <el-table :data="taskData" border style="width: 100%" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" align="center" />
                        <el-table-column prop="taskId" label="任务编号" width="150" />
                        <el-table-column prop="taskName" label="任务名称" width="150" />
                        <el-table-column prop="workstationId" label="工作站编号" width="150" />
                        <el-table-column prop="workstationName" label="工作站名称" width="150" />
                        <el-table-column prop="taskQuantity" label="排产数量" width="150" />
                        <el-table-column prop="computedQuantity" label="已生产数量" width="150" />
                        <el-table-column prop="startDate" label="开始时间" width="150" />
                        <el-table-column prop="endDate" label="预计完成时间" width="150" />
                        <!-- 修改表格中的操作列 -->
                        <el-table-column label="操作" width="150">
                            <template #default="{ row }">
                                <el-button type="text" size="small" @click="handleUpdate(row)">编辑</el-button>
                                <el-button type="text" size="small" @click="handleDelete(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>

            <div class="detail-footer">
                <el-button type="primary" @click="handleClose">关闭</el-button>
            </div>

            <!-- 表单弹窗 -->
            <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40%" :destroy-on-close="true"
                @close="handleDialogClose">

                <div class="task-edit-container"></div>
                <div class="task-form">
                    <el-form :model="data" label-width="120px">
                        <el-row :gutter="24">
                            <el-col :span="12">
                                <!--任务名称-->
                                <div class="form-group">
                                    <label>任务名称</label>
                                    <el-input v-model="data.taskName" placeholder="请输入任务名称"></el-input>
                                </div>

                            </el-col>

                            <el-col :span="12">
                                <!-- 工作站选择 -->
                                <div class="form-group">
                                    <label>工作站</label>
                                    <el-input style="width: 300px; margin-right: 10px;" v-model="data.workstationName"
                                        placeholder="请选择工作站" disabled :label="data.workstationName"></el-input>
                                    <el-button type="primary" @click="showOrderDialog">选择工作站</el-button>
                                </div>

                            </el-col>

                        </el-row>
                        <el-row :gutter="24">
                            <el-col :span="12">
                                <!-- 排产数量 -->
                                <div class="form-group">
                                    <label>排产数量</label>
                                    <el-input-number v-model="data.taskQuantity" :min="1" :max="100000"
                                        controls-position="right" placeholder="请输入排产数量">
                                    </el-input-number>
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <!-- 开始时间 -->
                                <div class="form-group">
                                    <label>开始时间</label>
                                    <el-date-picker v-model="data.startDate" type="datetime" placeholder="选择开始时间"
                                        value-format="YYYY-MM-DD HH:mm:ss">
                                    </el-date-picker>
                                </div>
                            </el-col>

                        </el-row>
                        <el-row :gutter="24">
                            <el-col :span="12">
                                <!-- 生产时长 -->
                                <div class="form-group">
                                    <label>生产时长 (小时)</label>
                                    <el-input-number v-model="data.productionTime" :min="1" :max="720"
                                        controls-position="right" placeholder="请输入生产时长">
                                    </el-input-number>
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <!-- 完成时间（只读） -->
                                <div class="form-group">
                                    <label>完成时间</label>
                                    <div class="time-display">{{ data.endDate }}</div>
                                </div>
                            </el-col>
                        </el-row>

                    </el-form>

                    <!-- 操作按钮 -->
                    <div class="form-actions">
                        <el-button type="primary" @click="handleConfirm" size="large">确定</el-button>
                        <el-button @click="handleCancel" size="large">取消</el-button>
                    </div>
                </div>
            </el-dialog>

            <!-- 工作站弹窗内容 -->
            <el-dialog :title="workstationdialogTitle" v-model="stationdialogVisible" width="60%"
                :destroy-on-close="true">
                <el-form :model="workstationForm" label-width="120px">
                    <el-row :gutter="20">
                        <el-col :span="6" :offset="0">
                            <el-form-item label="工作站编号">
                                <el-input v-model="workstationForm.workstationId" placeholder="请输入工作站编号"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" :offset="0">
                            <el-form-item label="所属工序">
                                <el-select v-model="workstationForm.processId" placeholder="请选择所属工序">
                                    <el-option v-for="item in proecss" :key="item.processId"
                                        :label="item.psName" :value="item.processId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" :offset="0">
                            <el-form-item label="所在车间">
                                <el-select v-model="workstationForm.workshopId" placeholder="请选择所在车间">
                                    <el-option v-for="item in workshops" :key="item.workshopcId"
                                        :label="item.workshopName" :value="item.workshopcId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" :offset="0">
                            <el-button type="primary" size="default" @click="searchWorkstation">搜索</el-button>
                            <el-button type="primary" size="default" @click="resetWorkstation">重置</el-button>
                        </el-col>
                    </el-row>
                </el-form>
                <el-table :data="page.records" border style="width: 100%" @row-click="handleSelectionChangeworkstation">
                    <el-table-column width="55" align="center">
                        <template #default="{ row }">
                            <el-radio v-model="selectedRowsworkstation" :value="row" @click.stop>
                            </el-radio>
                        </template>
                    </el-table-column>
                    <el-table-column prop="workstationId" label="工作站编号" />
                    <el-table-column prop="workstationName" label="工作站名称" />
                    <el-table-column prop="processStep.processName" label="所属工序" />
                    <el-table-column prop="workshop.workshopName" label="所在车间名称" />
                </el-table>

                <!-- 分页组件 -->
                <el-pagination @current-change="loadWorkstationData" v-model:currentPage="page.current"
                    :page-sizes="[2, 4, 6, 8, 10]" :page-size="page.size" :total="page.total" background>
                </el-pagination>


                <span>
                    <el-button @click="handleWorkstationCancel">取消</el-button>
                    <el-button type="primary" @click="handleWorkstationConfirm">确定</el-button>
                </span>
            </el-dialog>


        </el-card>
    </div>
</template>

<script setup>
import { ref, defineEmits, defineProps } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/api/request.js'

const router = useRouter()

let emits = defineEmits(['ref-table'])
let props = defineProps(["data"])

console.log(props.data)

// 表单数据
const formData = ref({})

const products = ref({})


let selectByPlanCode = () => {
    request({
        url: `production/plan/detailByPlanCode`,
        method: 'GET',
        params: {
            planCode: props.data.planCode
        }
    }).then(res => {
        formData.value = res.data[0]
        products.value = { ...formData.value.products }
        console.log(products.value.materialId)
        //查询产品的bom需求
        request({
            url: "/bom/selectBom",
            method: "get",
            params: { materialId: products.value.materialId }
        }).then(res => {
            products.value.bomDTOList = res.data
            console.log(res);
        })
        loadData()
        loadTaskData()
    })
}
selectByPlanCode()

//工序
const proecss = ref([])

// 加载工序数据
let loadData = () => {
    request({
        url: '/detail/Name',
        method: 'GET',
        params: { detailId: formData.value.routingId }
    }).then(res => {
        proecss.value = res.data.records
        console.log(proecss.value[1].processId)
    })
}



// 当前选中的工序ID
let currentProcessId = ref('')

// 处理选项卡点击事件
let handleTabClick = (tab) => {
    let processId = tab.props.name
    currentProcessId.value = processId
    loadTaskData(processId)
}

// 获取当前工序ID
let getCurrentProcessId = () => {
    return currentProcessId.value
}

//任务
let taskData = ref([])

// 生产任务数据
let loadTaskData = (processId) => {
    if (!processId) return
    request({
        url: '/schedule/task',
        method: 'GET',
        params: {
            processId: processId,
        }
    }).then(res => {
        taskData.value = res.data
    })
}

// 选中行
let selectedRows = ref([])

//弹窗属性
let dialogTitle = ref('')
let dialogVisible = ref(false)

// 处理行选中
const handleSelectionChange = (val) => {
    selectedRows.value = val
}

// 弹窗数据
const data = ref({
    taskId: '',
    taskName: '',
    workstationId: '',
    workstationName: '',
    taskQuantity: 0,
    productionTime: 0,
    startDate: '',
    endDate: '',
    processId: '' // 添加工序ID
})

/**
 * 弹窗新增
 */
let toInsert = () => {
    dialogTitle.value = '新增任务'
    dialogVisible.value = true
    // 重置表单数据，设置默认值
    data.value = {
        taskId: '',
        taskName: '',
        workstationId: '',
        workstationName: '',
        taskQuantity: 1, // 默认值
        productionTime: 1, // 默认值
        startDate: '',
        endDate: '',
        processId: getCurrentProcessId() // 获取当前选项卡的工序ID
    }
}

/**
 * 弹窗修改
 * @param row 当前行数据
 */
let handleUpdate = (row) => {
    dialogTitle.value = '修改任务'
    dialogVisible.value = true
    // 深拷贝数据，避免直接修改原数据
    data.value = JSON.parse(JSON.stringify(row))
}

/**
 * 弹窗删除
 * @param row 当前行数据
 */
let handleBatchDelete = () => {

    const taskIds = selectedRows.value.map(row => row.taskId)
    request({
        url: '/schedule/deletetask',
        method: 'DELETE',
        data: taskIds
    }).then(res => {
        console.log(res)
        // 刷新表格数据
        loadTaskData(currentProcessId.value)
        // 清空选中行
        selectedRows.value = []
    })
}

// 弹窗确认
let handleConfirm = () => {
    // 根据dialogTitle判断是新增还是修改
    if (dialogTitle.value === '新增任务') {
        handleAdd()
    } else {
        handleEdit()
    }
    dialogVisible.value = false
}

// 弹窗取消
let handleCancel = () => {
    dialogVisible.value = false
    resetForm()
}

// 弹窗关闭时的处理
const handleDialogClose = () => {
    resetForm()
    dialogVisible.value = false
}

// 工作站弹窗属性
let workstationdialogTitle = ref('')
let stationdialogVisible = ref(false)

let showOrderDialog = () => {
    workstationdialogTitle.value = '选择工作站'
    stationdialogVisible.value = true
    loadWorkshopData()
    loadWorkstationData()
}

let workshops = ref([])//车间

// 加载车间数据
let loadWorkshopData = () => {
    request({
        url: '/workshop/index',
        method: 'GET',
        params: {
            current: 1,
            size: 1000
        }
    }).then(res => {
        workshops.value = res.data.records
        console.log(workshops.value);
    })
}


// 加载工作站数据
let workstationForm = ref({})

//搜索
let searchWorkstation = () => {
    console.log(workstationForm.value);
    loadWorkstationData()
}

//重置
let resetWorkstation = () => {
    workstationForm.value = {}
    loadWorkstationData()
}
// 工作站分页数据
let page = ref({
    current: 1,    // 当前页码
    size: 1000,      // 每页显示条数
    total: 0,      // 总条数
    records: []    // 当前页数据
})

//查询工作站数据
let loadWorkstationData = () => {
    let params = {
        current: page.value.current,
        size: page.value.size,
        ...workstationForm.value
    }
    request({
        url: '/workstation/WorkshopName',
        method: 'GET',
        params,
    }).then(res => {
        console.log(res.data)
        page.value = res.data

    })
}

// 选中行
let selectedRowsworkstation = ref({})

// 处理行选中
const handleSelectionChangeworkstation = (row) => {
    selectedRowsworkstation.value = row
}

//确定工作站弹窗
let handleWorkstationConfirm = () => {
    data.value = selectedRowsworkstation.value
    stationdialogVisible.value = false
}
//取消工作站弹窗
let handleWorkstationCancel = () => {
    stationdialogVisible.value = false
}

// 重置表单数据
let resetForm = () => {
    data.value = {
        taskId: '',
        taskName: '',
        workstationId: '',
        workstationName: '',
        taskQuantity: 1,
        productionTime: 1,
        startDate: '',
        endDate: '',
        processId: ''
    }
}



// 修改任务方法（不再需要参数）
let handleEdit = () => {

    let proTaskData = ref({
        taskId: data.value.taskId,
        taskName: data.value.taskName,
        workstationId: data.value.workstationId,
        taskQuantity: data.value.taskQuantity,
        productionTime: data.value.productionTime,
        startDate: data.value.startDate
    })
        console.log(proTaskData.value)
    request({
        url: '/schedule/updatetask',
        method: 'put',
        data: proTaskData.value
    }).then(res => {
        console.log(res.data)
        // 刷新表格数据
        loadTaskData(currentProcessId.value)
        // 清空表单
        resetForm()
    })
}



// 新增任务方法
let handleAdd = () => {
    // 设置工序ID和其他必需字段
    data.value.processId = currentProcessId.value

    // 确保任务名称不为空
    if (!data.value.taskName || data.value.taskName.trim() === '') {
        ElMessage.error('请输入任务名称')
        return
    }

    // 确保工作站ID不为空
    if (!data.value.workstationId) {
        ElMessage.error('请选择工作站')
        return
    }

    //任务数据
    let proTaskData = ref({
        taskName: data.value.taskName,
        workstationId: data.value.workstationId,
        taskQuantity: data.value.taskQuantity,
        productionTime: data.value.productionTime,
        startDate: data.value.startDate
    })

    request({
        url: '/schedule/addtask',
        method: 'POST',
        data: proTaskData.value
    }).then(res => {
        console.log(res)
        loadTaskData(currentProcessId.value)
        resetForm()
    })
}


const handleClose = () => {
    router.push('/production/schedule')
    emits('ref-table')
}



</script>

<style scoped>
/* 新增样式 */
.material-warning {
    color: #f56c6c;
    font-weight: bold;
}

.material-safe {
    color: #67c23a;
}

.tab-label {
    display: flex;
    align-items: center;
}

.tab-label .el-tag {
    margin-left: 8px;
}

.task-form {
    padding: 25px;
}

.form-group {
    margin-bottom: 22px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: bold;
    color: #333;
}

.gantt-color-preview {
    width: 30px;
    height: 30px;
    border-radius: 4px;
    display: inline-block;
    vertical-align: middle;
    margin-left: 10px;
    border: 1px solid #ddd;
}

.time-display {
    background-color: #f9f9f9;
    padding: 10px 15px;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
    margin-top: 5px;
    color: #606266;
    width: 300px;
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #e4e7ed;
}

.el-input-number {
    width: 100%;
}

.el-date-editor {
    width: 100%;
}

.el-color-picker {
    vertical-align: middle;
}
</style>